// 盈利计算相关的共用工具函数

// 股票对象类型定义
interface Stock {
  id: string;
  code: string;
  name: string;
  quantity?: string | number;
  cost?: string | number;
  currentPrice?: number;
}

// 交易记录类型定义
interface Transaction {
  id: string;
  timestamp: string;
  direction: 'buy' | 'sell';
  quantity: string | number;
  amount: string | number;
  price?: string | number;
}

// 计算后的股票信息类型
interface CalculatedStock extends Stock {
  quantity: string;
  cost: string;
  currentValue: string;
  profit: string;
  profitRate: string;
  profitValue: number;
  currentPrice: number;
}

// 汇总盈利信息类型
interface TotalProfitInfo {
  totalProfit: string;
  totalProfitRate: string;
  totalCost: string;
  totalValue: string;
}

/**
 * 计算单只股票的盈利情况
 * @param stock - 股票对象
 * @param transactions - 交易记录数组
 * @param currentPrice - 当前价格
 * @returns 计算后的股票信息
 */
export function calculateStockProfit(
  stock: Stock, 
  transactions: Transaction[], 
  currentPrice: number | null = null
): CalculatedStock {
  // 按时间顺序排序交易记录
  const sortedTransactions = [...transactions].sort((a, b) => {
    return new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime();
  });
  
  // 计算总买入金额和总卖出金额
  let totalBuyAmount = 0;
  let totalSellAmount = 0;
  let totalQuantity = 0;
  
  sortedTransactions.forEach(transaction => {
    const quantity = parseFloat(String(transaction.quantity));
    const amount = parseFloat(String(transaction.amount));
    
    if (transaction.direction === 'buy') {
      totalBuyAmount += amount;
      totalQuantity += quantity;
    } else if (transaction.direction === 'sell') {
      totalSellAmount += amount;
      totalQuantity -= quantity;
      // 确保不会出现负数
      totalQuantity = Math.max(0, totalQuantity);
    }
  });
  
  // 如果没有交易记录，使用初始持仓数据
  if (transactions.length === 0 && stock.quantity && stock.cost) {
    totalQuantity = parseFloat(String(stock.quantity));
    totalBuyAmount = parseFloat(String(stock.cost));
  }
  
  // 持仓成本应该是当前持仓的总成本，即净投入金额
  const netCost = totalBuyAmount - totalSellAmount;
  
  // 如果没有提供当前价格，则使用持仓成本除以持仓数量作为当前价格（仅当持仓数量大于0时）
  if (currentPrice === null && totalQuantity > 0 && netCost > 0) {
    currentPrice = netCost / totalQuantity;
  }
  
  const currentValue = totalQuantity * (currentPrice || 0);
  const profit = currentValue - netCost;
  const profitRate = netCost > 0 ? (profit / netCost * 100) : 0;
  
  return {
    ...stock,
    quantity: totalQuantity.toFixed(2),
    cost: netCost.toFixed(2), // 持仓成本为净投入金额
    currentValue: currentValue.toFixed(2),
    profit: profit.toFixed(2),
    profitRate: `${profitRate.toFixed(2)}%`,
    profitValue: profit,
    currentPrice: currentPrice || 0
  };
}

/**
 * 计算汇总盈利
 * @param stocks - 股票数组
 * @param transactions - 交易记录对象
 * @param stockPrices - 股票价格对象
 * @returns 汇总盈利信息
 */
export function calculateTotalProfit(
  stocks: Stock[], 
  transactions: Record<string, Transaction[]>, 
  stockPrices: Record<string, number>
): TotalProfitInfo {
  if (stocks.length === 0) return { 
    totalProfit: '0.00', 
    totalProfitRate: '0.00%',
    totalCost: '0.00',
    totalValue: '0.00'
  };
  
  let totalCost = 0;
  let totalValue = 0;
  
  stocks.forEach(stock => {
    const stockTransactions = transactions[stock.id] || [];
    const currentPrice = stockPrices[stock.id] || null;
    const calculated = calculateStockProfit(stock, stockTransactions, currentPrice);
    totalCost += parseFloat(calculated.cost);
    totalValue += parseFloat(calculated.currentValue);
  });
  
  const totalProfit = totalValue - totalCost;
  const totalProfitRate = totalCost > 0 ? (totalProfit / totalCost * 100).toFixed(2) : '0.00';
  
  return {
    totalProfit: totalProfit.toFixed(2),
    totalProfitRate: `${totalProfitRate}%`,
    totalCost: totalCost.toFixed(2),
    totalValue: totalValue.toFixed(2)
  };
}